using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PHMEE.ConsoleTools.Ams;
using PHMEE.ConsoleTools.EnergyEfficiency;

namespace PHMEE.ConsoleTools;

public class CommandLineService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<CommandLineService> _logger;
    private readonly CancellationTokenSource _cts;

    public CommandLineService(IHostApplicationLifetime hostApplicationLifetime,
        IServiceProvider serviceProvider,
        ILogger<CommandLineService> logger)
    {
        _hostApplicationLifetime = hostApplicationLifetime;
        _serviceProvider = serviceProvider;
        _logger = logger;
        
        _cts = new CancellationTokenSource();
        
        // 注册 Ctrl+C 处理
        Console.CancelKeyPress += Console_CancelKeyPress;
    }
    
    private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
    {
        e.Cancel = true; // 防止默认的终止行为
        _cts.Cancel();
        _hostApplicationLifetime.StopApplication();
    }

    public async Task RunAsync()
    {
        try
        {
            // 显示当前工作目录
            var currentDirectory = Directory.GetCurrentDirectory();

            Console.ForegroundColor = ConsoleColor.Green;
            
            Console.WriteLine("命令：");
            Console.WriteLine("exit - 退出");
            Console.WriteLine("ping - pong");
            Console.WriteLine("pwd - 显示当前工作目录");
            Console.WriteLine("import-digital-config <VesselId> <FilePath> - 导入 AMS 开关量与机组的关联关系 Digital Config");
            Console.WriteLine("import-ovd-port <FilePath> - 导入 OVD Ports 港口");
            Console.WriteLine("import-vessel-ee-config <FilePath> - 导入 Vessel EE Config");
            Console.WriteLine("import-cii-factor <FilePath> - 导入 CII Reduction Factor");
            Console.WriteLine("import-log-abstract <VesselId> <FilePath> - 导入 Log Abstract");

            Console.ResetColor();
            
            Console.WriteLine($"当前的工作目录: {currentDirectory}");

            while (!_cts.Token.IsCancellationRequested)
            {
                Console.Write("> ");
                var command = Console.ReadLine()?.Trim();

                if (string.IsNullOrEmpty(command))
                {
                    continue;
                }

                var commandParts = command.Split(' ');
                switch (commandParts[0])
                {
                    case "ping":
                        Console.WriteLine("pong");
                        break;
                    case "exit":
                        _hostApplicationLifetime.StopApplication();
                        return;
                    case "pwd":
                        Console.WriteLine(currentDirectory);
                        break;

                    case DigitalConfigImporter.CommandName:
                        var digitalConfigImporter = new DigitalConfigImporter(_logger);
                        await digitalConfigImporter.RunCommandAsync(commandParts, _serviceProvider);
                        break;
                    case OvdPortImporter.CommandName:
                        var ovdPortImporter = new OvdPortImporter();
                        await ovdPortImporter.RunCommandAsync(commandParts, _serviceProvider);
                        break;
                    case VesselEeConfigImporter.CommandName:
                        var vesselEeConfigImporter = new VesselEeConfigImporter();
                        await vesselEeConfigImporter.RunCommandAsync(commandParts, _serviceProvider);
                        break;
                    case CiiReductionFactorImporter.CommandName:
                        var ciiReductionFactorImporter = new CiiReductionFactorImporter();
                        await ciiReductionFactorImporter.RunCommandAsync(commandParts, _serviceProvider);
                        break;
                    case LogAbstractImporter.CommandName:
                        var logAbstractImporter = new LogAbstractImporter();
                        await logAbstractImporter.RunCommandAsync(commandParts, _serviceProvider);
                        break;

                    default:
                        _logger.LogWarning("未知命令: {Command}", command);
                        break;
                }
            }
        }
        finally
        {
            Console.CancelKeyPress -= Console_CancelKeyPress;
            _cts.Dispose();
        }
    }
}